package com.jk.utils;
 
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


/**
 * 
 * 类: HttpClient <br>
 * 描述: httpclient工具类 <br>
 * 作者: song<br>
 * 时间: 2017年7月21日 下午3:15:27
 */
public class HttpClientUtil {
	
	static CloseableHttpClient client = null;
	static {
		//1、创建httpClient实例
		client = HttpClients.createDefault();
	}
	
	/**
	 * 
	 * 方法: get <br>
	 * 描述: get请求 <br>
	 * 作者: Teacher song<br>
	 * 时间: 2017年7月21日 下午3:15:25
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String get(String url,HashMap<String, Object> params){
/*		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("name", "张三");
		params.put("age", 18);*/
		try {
			//2、创建get对象
			HttpGet httpGet = new HttpGet();
			
			//3、拼接完成的get请求路径
			//a、hashmap的遍历：获取里面的key和value
			//b、拼接StringBuffer
			Set<String> keySet = params.keySet();
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.append(url).append("?t=").append(System.currentTimeMillis());
			for (String key : keySet) {
				stringBuffer.append("&").append(key).append("=").append(params.get(key));
			}
			
			httpGet.setURI(new URI(stringBuffer.toString()));
			//4、执行execute方法，发送请求
			CloseableHttpResponse execute = client.execute(httpGet);
			//5、获取请求的状态码
			int statusCode = execute.getStatusLine().getStatusCode();
			//判断请求是否成功
			if (200 != statusCode) {
				return "";
			}
			return EntityUtils.toString(execute.getEntity(), "utf-8");
		}catch (Exception e) {
			//6、关闭连接
			try {
				client.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
	 * 方法: post <br>
	 * 描述: post请求 <br>
	 * 作者: Teacher song<br>
	 * 时间: 2017年7月21日 下午3:20:31
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String post(String url,HashMap<String, Object> params) {
		try {
			//创建post请求对象
			HttpPost httpPost = new HttpPost();
			//设置路径
			httpPost.setURI(new URI(url));
			
			//设置post请求参数
			//a、hashmap的遍历：获取里面的key和value
			//b、拼接list
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				NameValuePair e = new BasicNameValuePair(key, params.get(key).toString());
				parameters.add(e);
			}
			
			HttpEntity entity = new UrlEncodedFormEntity(parameters , "utf-8");
			httpPost.setEntity(entity);
			
			//执行：发送请求
			CloseableHttpResponse execute = client.execute(httpPost);
			//获取请求的状态码
			int statusCode = execute.getStatusLine().getStatusCode();
			if (200 != statusCode) {
				return "";
			}
			return EntityUtils.toString(execute.getEntity(), "utf-8");
		}catch (Exception e) {
			//6、关闭连接
			try {
				client.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}			
			e.printStackTrace();
			return null;
		}
	}
	
	//发送短信验证码：给header传参
	public static String post2(String url,HashMap<String, Object> params,HashMap<String, Object> HeaderParams) {
		try {
			//创建post请求对象
			HttpPost httpPost = new HttpPost();
			//设置路径
			httpPost.setURI(new URI(url));
			
			//设置请求的header
			Set<String> headerKey = HeaderParams.keySet();
			for (String key : headerKey) {
				httpPost.addHeader(key, HeaderParams.get(key).toString());
			}
			
			//设置post请求参数
			//a、hashmap的遍历：获取里面的key和value
			//b、拼接list
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				NameValuePair e = new BasicNameValuePair(key, params.get(key).toString());
				parameters.add(e);
			}
			
			HttpEntity entity = new UrlEncodedFormEntity(parameters , "utf-8");
			httpPost.setEntity(entity);
			
			//执行：发送请求
			CloseableHttpResponse execute = client.execute(httpPost);
			//获取请求的状态码
			int statusCode = execute.getStatusLine().getStatusCode();
			if (200 != statusCode) {
				return "";
			}
			return EntityUtils.toString(execute.getEntity(), "utf-8");
		}catch (Exception e) {
			//6、关闭连接
			try {
				client.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}			
			e.printStackTrace();
			return null;
		}
	}
	
	//发送短信
	public static String sendMsg(String phone) {
		String url = "https://api.netease.im/sms/sendcode.action";

		HashMap<String, Object> headerParams = new HashMap<String, Object>();
		//开发者平台分配的appkey
		//String appKey = "e79c51e80064da39f23f5ddb124a39be";
		//String appKey = "95c4e016ac72a5f252ec5b99032bf9bb";///xz
		//String appKey = "f86195afe3e7c1961467720bdfbf72b8"; //sec
		String appKey = "1b7d6f36dc8542ceeccaddf57ffd8374"; //wh
		//随机数6位  100000 999999
		long nonce = Math.round(((Math.random()*899999+100000)));
		//当前UTC时间戳，从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
		long curTime = System.currentTimeMillis()/1000;
		//SHA1(AppSecret + Nonce + CurTime)，三个参数拼接的字符串，进行SHA1哈希计算，转化成16进制字符(String，小写)
		//String appSecret = "d09629e591b3";
		//String appSecret = "3e53c52df928";//xz
		//String appSecret = "c85eeb50dadf";//sec
		String appSecret = "006e5f4f4f8c";//wh
		String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce+"", curTime+"");
		headerParams.put("AppKey", appKey);
		headerParams.put("Nonce", nonce);
		headerParams.put("CurTime", curTime);
		headerParams.put("CheckSum", checkSum);
		headerParams.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

		
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("mobile",phone);
		//params.put("templateid","14841053");
		//params.put("templateid","19478129");//xz
		//params.put("templateid","19469147");//sec
		params.put("templateid","19480194");//wh
		params.put("authCode",nonce);//验证码
		
		String str = HttpClientUtil.post2(url, params, headerParams);
/*		JSONObject parseObject = JSONObject.parseObject(str);
		int code = parseObject.getIntValue("code");
		if(code!=200){
			System.out.println("请求失败："+code);
		}else{
			System.out.println("短信发送成功！"+code);
		}
		*/
		//请求结果，验证码
		return str;
	}
}
